<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,initial-scale=1.0,width=device-width"/>
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>inote 云记事</title>
    <link rel="stylesheet" type="text/css" href="./css/api.css" />
    <link rel="stylesheet" type="text/css" href="./css/layout.css" />
    <link rel="stylesheet" type="text/css" href="./css/container.css" />
    <link rel="stylesheet" type="text/css" href="./css/component/bar.css" />
    <link rel="stylesheet" type="text/css" href="./css/component/panel.css" />
    <link rel="stylesheet" type="text/css" href="./css/component/button.css" />
    <link rel="stylesheet" type="text/css" href="./css/component/animated.css" />
    <!-- 主页样式 -->
    <link rel="stylesheet" type="text/css" href="./css/main.css" />
</head>
<body>
    <div id="wrap">
        <div id="header" class="ino-bar home-bar">
            <table class="ino-bar-content">
                <tr>
                    <td>
                        <span class="bar-user-img animated" onclick="openAppDetail()">
                            <img class="userimg" src="./image/user/logo.png">
                        </span>
                    </td>
                    <td class="bar-right" align="right">
                        <div class="bar-tab bar-tab-time" tapmode="tabActive" onclick="openWebpage( '2' )">
                            <img class="listTab" src="./image/png/home/clock.png">
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        <div id="main">
            <div class="frame-view atlas">
                
                <button class="mui-btn mui-btn--primary mui-btn--fab menuAnimated" id="menu" onclick="clickMenu()">
                    <img class="menuBtn" src="./image/png/home/add.png">
                </button>            
            </div>
        </div>
    </div>
    
</body>
<script type="text/javascript" src="./script/api.js"></script>
<script type="text/javascript">
    // =============================================
    // 页面的全局变量
    var winWidth = $api.dom('#wrap').offsetWidth;
    var frameView = $api.dom('.frame-view');
    var listviewWidth = parseInt(winWidth/3);
    var listviewHeight = ((winWidth-28)/3);

    apiready = function(){
        // 首先加载监听事件
        aEventListener();

        // 创建inote.db
        // 在第一次运行时创建表
        // 在之后每次打开，会检查是否存在表
        var db = api.require('db');
        createDB();

        // 打开数据库，加载数据
        db.openDatabase({
            name: 'inote',
            path: 'fs://inote.db'
        }, function(ret, err){
            if(ret.status){
                sel('Text');
                closeDatabase();
            }
        });

        // =============================================
        // 打开inote.db
        // 插入新的数据，删除数据，修改数据,一次一条
        // 查询数据并读取出来，一次多条
        function closeDatabase() {
            db.closeDatabase({name:'inote'});      
        };
        function executeSql(sql) {
            db.executeSql({
                name: 'inote',
                sql: sql
            }, function(ret, err){
                
            });
        };
        function selectSql(sql) {
            db.selectSql({
                name:'inote',
                sql: sql
            }, function(ret, err){
                if(ret.status){
                    var datas = ret.data;
                    if (datas.length === 0) {
                        // alert('快创建记事吧');
                        openToast('快创建记事吧');
                    }else{
                        loadListView(datas);
                    };
                }
            });
        };

        // =============================================
        // 具体db的操作
        // @table, @id, @type, @detail
        function insert(table, id, type, detail) {
            var sql = "INSERT INTO "+table+" VALUES ('"+id+"', '"+type+"', '"+detail+"', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)";
            executeSql(sql);
        };
        function update(table, id, oldId) {
            var sql = "UPDATE "+table+" SET id = '"+id+"', update_time = CURRENT_TIMESTAMP WHERE id = "+oldId;
            executeSql(sql);
        };
        function del(table, id) {
            var sql = "DELETE FROM "+table+" WHERE id = '"+id+"'";
            executeSql(sql);
        };
        function sel(table) {
            var sql = "SELECT * FROM "+table+"";
            selectSql(sql);
        };
    };

    // ==============================================
    // 创建inote.db
    // 此方法与写入方法不同
    // ==============================================
    function createDB() {
        var db = api.require('db');
        db.openDatabase({
            name: 'inote',
            path: 'fs://inote.db'
        }, function(ret, err){
            if(ret.status){
                // 第一次打开app首先创建库，然后创建各个表
                var createTextSql = "CREATE TABLE Text(id INTEGER PRIMARY KEY AUTOINCREMENT,type varchar(1) DEFAULT NULL,detail text,create_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,update_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)";
                var createScheduleSql = "CREATE TABLE Schedule(id INTEGER PRIMARY KEY AUTOINCREMENT,type varchar(1) DEFAULT NULL,status varchar(1) DEFAULT NULL,title varchar(20),detail text,startTime varchar(20),endTime varchar(20),create_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,update_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)";
                executeNewSql(createTextSql);
                executeNewSql(createScheduleSql);
                // 各个表创建完成后,记录下来,DBandTableCreated
                // $api.setStorage('DBandTableCreated','ok');
            }
        });
    };
    function executeNewSql(sql) {
        var db = api.require('db');
        db.executeSql({
            name: 'inote',
            sql: sql
        }, function(ret, err){
            if(ret.status){
                // api.alert({msg:'执行SQL成功'});
            }
        });
    };

    // =============================================
    // 监听事件
    function aEventListener() {
        api.addEventListener({
            name: 'keyback',
        }, function( ret, err ){
            if ( ret ) {
                openBottomMenu();
                // api.toLauncher();
            };
        });
        // menu是否被打开 
        api.addEventListener({
            name: 'menuOpened'
        }, function(ret, err){
            if( ret ){
                haveMenuOpened();
            }
        });
        // menu的隐藏与显示
        api.addEventListener({
            name: 'hide'
        }, function(ret, err){
            if( ret ){
                hideMenu();
            }
        });
        api.addEventListener({
            name: 'closeSlide'
        }, function(ret, err){
            if( ret ){
                showMenu();
            }
        });
        api.addEventListener({
            name: 'menuClosed'
        }, function(ret, err){
            if( ret ){
                // alert( JSON.stringify( ret ) );
                var menu = $api.dom('#menu');
                $api.toggleCls(menu, 'open');
            }
        });
        api.addEventListener({
            name: 'changeMenu'
        }, function(ret, err){
            if( ret ){
                // alert( JSON.stringify( ret ) );
                var menu = $api.dom('#menu');
                $api.removeCls(menu, 'open');
            }
        });
        api.addEventListener({
            name: 'reloadMemorandum'
        }, function(ret, err){
            if( ret ){
                // alert( JSON.stringify( ret ) );
                var menu = $api.dom('#menu');
                $api.removeCls(menu, 'open');
                api.openWin({
                    name: 'root',
                    reload: true
                });
            }
        });
    };

    // =============================================
    // 在事件menuOpened发生后被调用，作用关闭menu
    // 并且改变样式，然后去除keyback，再添加
    function haveMenuOpened() {
        api.addEventListener({
            name: 'keyback',
        }, function( ret, err ){
            if ( ret ) {
                // alert( JSON.stringify( ret.value.close ) );
                api.closeFrame({name: 'menu'});
                api.sendEvent({name: 'changeMenu'});
                api.removeEventListener({name: 'keyback'});
                api.addEventListener({
                    name: 'keyback',
                }, function( ret, err ){
                    if ( ret ) {
                        openBottomMenu();
                    };
                });
            }
        });
    };

    // =============================================
    // 打开schedule.html
    function openWebpage( index ) {
        api.openWin({
            name: 'schedule',
            url: './html/schedule.html',
            reload: true,
            pageParam: {
                name: name,
                pagename: '任务清单'
            }
        });
    };

    // =============================================
    // 发送隐藏事件
    function sendEvent() {
        api.sendEvent({
            name: 'hide'
        });
    };

    // =============================================
    // 提示框
    function openToast(msg) {
        api.toast({
            msg: msg,
            duration: 1500,
            location: 'middle'
        });
    };

    // =============================================
    // 当点击返回键，选择后台运行还是退出
    function openBottomMenu() {
        api.openFrame({
            name: 'quit',
            url: './html/quit.html',
            bounces: false,
            bgColor: 'rgba(0,0,0,0.4)',
            rect: {
                x: 0,
                y: 0,
                w: 'auto',
                h: 'auto'
            }
        });
    };
    // =============================================
    // =============================================
    // =============================================
    // =============================================
    // =============================================
    // 菜单打开的动画，css3完成,js调用
    // 只有菜单可选，其余不可选
    function clickMenu() {
        var thisMenu = $api.dom('#menu');
        $api.toggleCls(thisMenu, 'open');
        setTimeout(openMenuFrame, 200);
    };
    // =============================================
    // 打开菜单
    var openMenuFrame = function() {
        api.animation ({
            name: 'menu',
            duration: 300,
            curve: 'ease_out'
        });
        api.openFrame({
            name: 'menu',
            url: './html/menu.html',
            rect: {
                x: 0,
                y: 0,
                w: 'auto',
                h: 'auto'
            },
            bounces: false,
            bgColor: 'rgba(0,0,0,0.4)',
            vScrollBarEnabled: false,
            hScrollBarEnabled: false
        });
    };
    // =============================================
    // 隐藏menu
    function hideMenu() {
        $api.addCls($api.dom('#menu'), 'hide');
    };

    // =============================================
    // 显示menu
    function showMenu() {
        $api.removeCls($api.dom('#menu'), 'hide');
    };

    // =============================================
    // 数据成功被访问后，被转换成数组的形式保存
    // 最终显示在首页上
    // 写入全部的笔记内容
    function loadListView(data) {
        for (var i = data.length - 1; i >= 0; i--) {
            checkType(data[i].id, data[i].type, data[i].detail);
        };
    };
    // =============================================
    // 判断笔记的类型
    function checkType(id, num, detail) {
        if (num === '1') {
            htmlWordCode(id, detail);
        } else if (num === '2') {
            htmlImageCode(id, detail);
        } else if (num === '3') {
            htmlRecordCode(id, detail);
        } else {
            api.alert({msg: '错误信息', buttons: ['确定']});
        };
    };

    // =============================================
    // 写入的word笔记html代码
    // @details, 页面的全局变量，用来保存word的detail信息
    var details = new Array();
    // 在htmlWordCode()中被赋值，在openWordPage()中传递给其他的页面

    function htmlWordCode(id, detail) {
        var word = wordLength(detail);
        details[parseInt(id)] = detail;
        var codetxt = '<div class="listview atl-2" onclick="openWordPage('+id+')"><div class="listtab"><div class="listtab-content" style="height: '+listviewHeight+'px;"><div class="word"><h5>'+ word +'</h5></div></div></div></div>';
        $api.prepend(frameView, codetxt);
    };

    // =============================================
    // 写入的image笔记html代码
    function htmlImageCode(id, detail) {
        var imgTitleHeight = listviewHeight*0.25;
        var detailArray = detail.split(',');
        var imgComSrc = api.fsDir+'/photos/'+detailArray[1];
        details[parseInt(id)] = detail;
        var codetxt = '<div class="listview atl-2" onclick="openImgPage('+id+')"><div class="listtab"><div class="listtab-content" style="height: '+listviewHeight+'px;"><div class="image"><div class="imgTitle" style="height: '+imgTitleHeight+'px;line-height: '+imgTitleHeight+'px;">'+ detailArray[2] +'</div><img id="img_'+id+'" src="'+ imgComSrc +'"></div></div></div></div>';
        $api.prepend(frameView, codetxt);
        checkWidthAndHeight(imgComSrc, id);
    };

    // =============================================
    // 写入的record笔记html代码
    function htmlRecordCode(id, detail) {
        var detailArray = detail.split(',');
        Number.prototype.formatTime=function(){
            // 计算
            var h=0,i=0,s=parseInt(this);
            if(s>60){
                i=parseInt(s/60);
                s=parseInt(s%60);
                if(i > 60) {
                    h=parseInt(i/60);
                    i = parseInt(i%60);
                }
            }
            // 补零
            var zero=function(v){
                return (v>>0)<10?"0"+v:v;
            };
            return [zero(h),zero(i),zero(s)].join(":");
        };
        // 将秒数转换成为时间格式
        details[parseInt(id)] = detail;

        var imgTitleHeight = listviewHeight*0.25;
        var codetxt = '<div class="listview atl-2" onclick="openMicPage('+id+')"><div class="listtab"><div class="listtab-content" style="height: '+listviewHeight+'px;"><div class="record"><div class="imgTitle" style="bottom: 0px;height: '+imgTitleHeight+'px;line-height: '+imgTitleHeight+'px;">'+ Number(detailArray[1]).formatTime() +'</div><img class="recordImg" src="./image/play_circle_outline.png"></div></div></div></div>';
        $api.prepend(frameView, codetxt);
    };

    // =============================================
    // 计算显示便签的文字长度
    // @word, 返回文本
    function wordLength(word) {
        var m = (listviewWidth - 16) * (listviewWidth - 16);
        var wordNum = parseInt(m/300);
        var changeWord = word.substr(0, wordNum);
        return changeWord;
    };

    // =============================================
    // 打开笔记，传入数据@id, @detail
    function openWordPage( id ) {
        var detail = details[parseInt(id)];
        api.openWin({
            name: 'edit_webpage',
            url: './html/edit_webpage.html',
            pageParam: {
                id: id.toString(),
                detail: detail
            },
            animation: {
                type: 'fade',
                duration: 300   
            }
        });
    };
    
    // =============================================
    // 开始播放录音，变量@id, @detail
    function openMicPage( id ) {
        var detail = details[parseInt(id)];
        api.openWin({
            name: 'mic_webpage',
            url: './html/mic_webpage.html',
            pageParam: {
                id: id.toString(),
                detail: detail
            },
            animation: {
                type: 'fade',
                duration: 300   
            }
        });
    };

    // =============================================
    // 浏览照片，变量@id, @detail
    function openImgPage( id ) {
        var detail = details[parseInt(id)];
        api.openWin({
            name: 'img_webpage',
            url: './html/img_webpage.html',
            pageParam: {
                id: id.toString(),
                detail: detail
            },
            animation: {
                type: 'fade',
                duration: 300   
            }
        });
    };
    
    // =============================================
    // var img_url = '../image/bg/b1.jpg';
    // checkWidthAndHeight(img_url);
    // 判断图片宽高
    function checkWidthAndHeight(src, id) {
        var img = new Image();
        var imgWidth,imgHeight;
        img.src = src;

        img.onload = function() {
            imgWidth = img.width;
            imgHeight = img.height;
            if (imgWidth > imgHeight) {
                $api.css($api.dom('#img_'+id), 'width: auto;height: 100%;');
            };
        };
    };

    // =============================================
    // 添加应用程序详情
    function openAppDetail(){
        api.openWin({
            name: 'app_detail',
            url: './html/app_detail.html',
            animation: {
                type:"movein",
                subType:"from_bottom",
                duration:300
            }
        });
    }
</script>
</html>